import { App } from 'vue'
import { logger } from '@/instance'

export default {
  install(app: App, opt: any) {
    app.directive('dragger', {
      /**
       * 模拟拖拽
       *
       * @param {*} el
       * @param {*} binding
       */
      mounted(el: any, binding) {
        const callback = binding.value
        logger.log('plugins/dragger', 'dragger mounted', arguments)
        let x = 0
        let y = 0
        const mousemove = (e: MouseEvent) => {
          let ret = callback({
            x: e.x - x,
            y: e.y - y,
            finished: false,
          })
          // 缓冲值  未处理的值 逆向时抵消
          x = e.x - ret.x
          y = e.y - ret.y
        }
        const mouseup = (e: MouseEvent) => {
          callback({
            x: e.x - x,
            y: e.y - y,
            finished: true,
          })
          window.removeEventListener('mousemove', mousemove)
          window.removeEventListener('mouseup', mouseup)
        }
        el.onmousedown = (e: MouseEvent) => {
          x = e.x
          y = e.y
          e.preventDefault()
          window.addEventListener('mousemove', mousemove)
          window.addEventListener('mouseup', mouseup)
        }

        //
      },
      beforeUnmount(el: any) {
        logger.log('plugins/dragger', 'dragger before unmounted', arguments)
        el.onmousedown = null
      },
    })
  },
}
